package thead;

import java.util.Random;

public class Demo6 {
    public static int count1 = 0;
    public static int count2 = 0;
    public static void main(String[] args) throws InterruptedException {
        long beg = System.currentTimeMillis();
        int[] arrays = new int[10000000];
        Object o1 = new Object();
        Object o2 = new Object();
        // 生成1000w的数组
        Thread t1 = new Thread(()->{
            synchronized (o1) {
                Random r = new Random();
                for(int i = 0;i < arrays.length;i++) {
                    arrays[i] = r.nextInt(1,101);
                }
            }
        });
        t1.start();
        Thread t2 = new Thread(()->{
            synchronized (o2) {
                Random r = new Random();
                for (int i = 1; i < arrays.length; i += 2) {
                    arrays[i] = r.nextInt(1, 101);
                }
            }
        });
        t2.start();
        // 统计偶数 下标
        Thread t3 = new Thread(()->{
            synchronized (o1) {
                Random r = new Random();
                for (int i = 0; i < arrays.length; i++) {
                    count1 += arrays[i];
                }
            }
        });
        t3.start();
        // 统计奇数 下标
        Thread t4 = new Thread(()->{
            synchronized (o2) {
                Random r = new Random();
                for (int i = 1; i < arrays.length; i += 2) {
                    count2 += arrays[i];
                }
            }
        });
        t4.start();
        while(t3.isAlive() || t4.isAlive()) {
        }
        System.out.println("总和：" + count1 + count2);
        long end = System.currentTimeMillis();
        System.out.println("程序花费时间：" + (end - beg));
    }
}
